<?php
/**
 * 闪购 model类
 * Created by PhpStorm.
 * User: 章利桂
 * Date: 2016/9/7
 * Time: 11:48
 */
class flashBuyModel
{
    const flashSchemeHead = 'joggers://flashSales/';
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }

    /**
     * 查询闪购列表
     */
    public function getFlashBuyList($params) {
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $limitNum  = $params['limit'] ? (int)$params['limit'] : 10;
        $title     = isset($params['name']) ? trim($params['name']) : '';
        $code      = isset($params['code']) ? trim($params['code']) : '';
        $status    = isset($params['status']) ? (int)$params['status'] : 0;
        $type    = isset($params['type']) ? (int)$params['type'] : 0;
        $startTime = isset($params['startTime']) ? $params['startTime'] : '';
        $endTime   = isset($params['endTime']) ? $params['endTime'] : '';
        $is_shihuo = isset($params['is_shihuo']) ? 1 : 0;
        $where = '1=1';
        if ($title) {
            $where .=' and title like '."'%$title%'";
        }
        if ($code) {
            $where .=' and code like '."'%$code%'";
        }
        if ($status) {
            if ($status == 1) {
                $where .= ' and status=0';
            } else if($status == 2) {
                $where .= ' and status=5';
            }  else if($status == 3) {
                $where .= ' and status=10';
            }
        } else {
            $where .= ' and status >=0';
        }
        if($type){
            $where .= ' and type='.$type;
        }
        if ($startTime) {
            $where .= ' and start_time >='.strtotime($startTime);
        }
        if ($endTime) {
            $where .= ' and end_time <='.strtotime($endTime);
        }
        if($is_shihuo){
            $where .= ' and shihuo_grouponid >0';
        }
        $sql ="select * from r_flash_sales where $where order by id desc limit $start,$limitNum";
        $cntsql ="select count(1) as cnt from r_flash_sales where $where";
        $this->total =  $this->db->getOne("$cntsql");
        return $this->db->getAll($sql);
    }

    /**
     * 新增闪购
     */
    public function addFlashBuy(array $params) {
        $id = (int)$params['id'];
        $title = $params['title'];
        $image = $params['image'];
        $images = $params['images'];
        $warmupTime = $params['warmupTime'];
        $startTime = $params['startTime'];
        $endTime = $params['endTime'];
        $costPrice = $params['costPrice'];
        $imageContent = $params['imageContent'];
        $optionContent = $params['optionContent'];
        $weidian_link = $params['weidian_link'];
        $low_price = $params['low_price'];
        $shihuo_grouponid = $params['shihuo_grouponid'];
        $gear_id = $params['gear_id'];
        $status = $params['status'];
        $type = $params['type'];
        $data = array(
            'title'=>$title,
            'image'=>$image,
            'images'=>$images,
            'warmup_time'=>$warmupTime ? strtotime($warmupTime) : 0,
            'start_time'=>strtotime($startTime),
            'end_time'=>strtotime($endTime),
            'cost_price'=>(double)$costPrice,
            'image_content'=>$imageContent,
            'option_content'=>$optionContent,
            'weidian_link'=>$weidian_link,
            'low_price'=>$low_price,
            'shihuo_grouponid' =>$shihuo_grouponid, 
            'gear_id' =>$gear_id,
            'type' =>$type,
            'status' =>$status,
        );
        if(empty($shihuo_grouponid)){
            unset($data['shihuo_grouponid']);
        }

        if (!$id) {
            $code  = $this->generateFlashCode();
            $data['code'] = $code;
            $data['status'] = $status;
            $data['create_time'] = time();
            $result= $this->db->insertRow('r_flash_sales',$data,mysqldb::INSERT_COMMON);
        } else {
            //$data['id'] = $id;
            $setStr = common::arrayToString($data);
            $sql = "update r_flash_sales set $setStr where id= $id";
            $result= $this->db->update($sql);
        }

        return $result;
    }

    /**
     * 更新闪购原价，总库存（后台设置）
     */
    public function setFlashCostPrice($flashId,$totalNum) {
       return  $this->db->update("update r_flash_sales set total_num=$totalNum,sale_num=0 where id=$flashId");
    }

    /**
     * 生成货品code
     */
    public function generateFlashCode() {
        $code = substr('F'.md5(microtime(true)),0,9);
        $sql = "select id from r_flash_sales where code = '$code'";
        $id = $this->db->getOne($sql);
        if ($id) {
            return $this->generateFlashCode();
        }
        return $code;
    }

    /**
     * 闪购信息
     */
    public function getFlashBuyInfo($flashId,$fields='*') {
        return  $this->db->getRow("select $fields from r_flash_sales where id=$flashId");
    }

    /**
     * 闪购信息
     * @param $flashCode 闪购CODE
     * @param string $fields
     * @return mixed
     */
    public function getFlashBuyInfoByCode($flashCode,$fields='*') {
        return   $this->db->getRow("select $fields from r_flash_sales where code='$flashCode'");
    }

    /**
     * 更新闪购状态
     * @param $type  1 删除闪购  2 结束闪购
     * @param $flashId
     * @return mixed
     */
    public function saveFlashStatus($type,$flashId) {
        if ($type == 1) {
            $sql = "update r_flash_sales set status = -5 where id=$flashId ";
        } else if($type == 2) {
            $sql = "update r_flash_sales set status = 10 where id=$flashId ";
        } else if ($type == 3) {
            $sql = "update r_flash_sales set status = 5 where id=$flashId ";
        } else {
            return 0;
        }
        return $this->db->update($sql);
    }

    /**
     * 查询闪购是否显示提醒（开始前显示）
     */
    public function getFlashIsStart($flashId) {
        return $this->getFlashBuyInfo($flashId,'id,status');
    }

    /**
     * 售出闪购商品，总数量减少,给定时器下架闪购提供参考
     * @param $id
     * @param int $num
     * @return mixed
     */
    public function saleFlashGoods($id,$num=1) {
        $sql = "update r_flash_sales set sale_num=sale_num+$num where id=$id";
        return $this->db->update($sql);
    }

    /**
     * 订单超时未付款，库存回滚
     * @param $id
     * @param int $num 回滚数量
     * @return mixed
     */
    public function rollbackFlashGoodsSaleNum($id,$num=1) {
        $sql = "update r_flash_sales set sale_num=sale_num-$num where id=$id";
        return $this->db->update($sql);
    }

    /**
     * cron  闪购未开始 变为 进行中
     */
    public function autoUpShelf() {
        $now = time();
        //查询全部未开始闪购
       $list =  $this->db->getAll("select id,end_time from r_flash_sales where type in(1,2) and  status = 0 and $now >= start_time");
        if (!$list) {
            echo '--1--'.date('Y-m-d H:i:s').' 全部未开始闪购列表为空'.PHP_EOL;
           return false;
        }
        foreach ($list as $key=>$val) {
            //检测结束时间
            if ($now > $val['end_time']) {//异常-已结束
                echo '--1--'.date('Y-m-d H:i:s').'id：'.$val['id'].'---'.date('Y-m-d H:i:s',$now). '大于结束时间:' .date('Y-m-d H:i:s',$val['end_time']).' 异常-已结束'.PHP_EOL;
                $sql = "update r_flash_sales set status = 10 where id={$val['id']}";
                $this->db->update($sql);
                continue;
            }
            $r = $this->saveFlashStatus(3,$val['id']);//进行中
            if ($r) {
                echo '--1--'.date('Y-m-d H:i:s').'id：'.$val['id'].'---'.' 成功变更为-进行中'.PHP_EOL;
            } else {
                echo '--1--'.date('Y-m-d H:i:s').'id：'.$val['id'].'---'.' 失败变更为-进行中'.PHP_EOL;
            }
        }
    }

    /**
     * cron 闪购进行中 变为 已结束
     */
    public function autoDownShelf() {
        $now = time();
        //查询全部闪购
        $list =  $this->db->getAll("select id,total_num,sale_num,end_time from r_flash_sales where type in (1,2) and status = 5");
        if (!$list) {
            echo '--2--'.date('Y-m-d H:i:s').' 全部进行中闪购列表为空'.PHP_EOL;
            return false;
        }
        foreach ($list as $key=>$val) {
            //闪购结束时间已到
            if($now >= $val['end_time']) {
                echo '--2--'.date('Y-m-d H:i:s').'id：'.$val['id'].'---'.date('Y-m-d H:i:s',$now). '大于结束时间:' .date('Y-m-d H:i:s',$val['end_time']).' 闪购结束时间已到-已结束'.PHP_EOL;
                $this->saveFlashStatus(2,$val['id']);
                continue;
            }
            //商品已卖完
            if ($val['total_num'] >0 && (bcsub($val['total_num'],$val['sale_num']) <= 0)) {
                $r = $this->saveFlashStatus(2,$val['id']);
                if ($r) {
                    echo '--2--'.date('Y-m-d H:i:s').'id：'.$val['id'].'---'.' 商品已卖完，成功变更为-已结束'.PHP_EOL;
                } else {
                    echo '--2--'.date('Y-m-d H:i:s').'id：'.$val['id'].'---'.' 商品已卖完，失败变更为-已结束'.PHP_EOL;
                }
                continue;
            }
        }
    }
    /************************************************闪购提醒START**********************************************/
    /**
     * 增加提醒
     */
    public function flashRemind($uid, $cid, $flashId) {
        $data = array(
            'object_id'=>$flashId,
            'uid'=>$uid,
            'cid'=>$cid,
            'type'=>1,
            'status'=>0,
            'create_time'=>time(),
            'url'=>self::flashSchemeHead.$flashId
        );
        $r =$this->db->insertRow('r_object_remind',$data,0);
        return $r;
    }

    /**
     * 取消提醒
     */
    public function disFlashRemind($uid, $flashId) {
        $sql = "update r_object_remind set status=-5 where uid=$uid and object_id=$flashId and status=0 and type=1";
        $r =$this->db->update($sql);
        return $r;
    }

    /**
     * 查询提醒是否开启
     */
    public function getRemindStatus($uid, $flashId) {
        $sql = "select id from r_object_remind where uid=$uid and object_id=$flashId and status =0 and type =1";
        return $this->db->getOne("$sql");
    }

    /**
     * 更新提醒状态
     */
    public function saveRemindStatus($remindId,$status) {
        $now = time();
        if ($status == 5) {
            return $this->db->update("update r_object_push set status=$status,start_time=$now where id=$remindId");
        } else if ($status == 10) {
            return $this->db->update("update r_object_push set status=$status,end_time=$now where id=$remindId");
        }
    }

    /**
     * 提醒推送
     * @params type 1 闪购提醒
     */
    public function sendRemind($type=1,$remindInfo) {
        set_time_limit(0);
        $is_success = 0;
        $mipush = $this->base->loadLib('mipush');
        if ($type ==1) {
                //查询闪购是否开始(闪购变更为进行中状态之前3分钟)
               // $info = $this->getFlashBuyInfo($remindInfo['object_id'],'id,title,status,start_time');
//                if (!$info || $info['status'] <> 0) {
//                     exit; //无需提醒
//                }
//                if ((bcsub(time(),$info['start_time']) > 3*60) || (bcsub(time(),$info['start_time']) < 0)) {
//                    exit; //无需提醒
//                }

                // 发送Android通知
                $androidData = array(
                    'clients' => array(),
                    'expiry' => time() + 3600,
                    'payload' => array(
                        'aps' => array(
                            'alert' => array(
                                'body' => '你关注的'.$remindInfo['title'].'已经开始了，点击查看',
                                'title' => '限时闪购开启',
                                'action-loc-key' => '',
                                'loc-key' => '',
                                'loc-args' => '',
                                'launch-image' => '',
                            ),
                            // 'badge' => 3,
                            'sound' => 1,
                        ),
                        'url' => $remindInfo['url'],//推送的地址
                        'args' => "",
                    ),
                );

                //ios消息推送
                $iosData = array(
                    'tokens' => array(),
                    'expiry' => time() + 1800,
                    'payload' => array(
                        'aps' => array(
                            'alert' => array(
                                'body' =>  '你关注的'.$remindInfo['title'].'已经开始了，点击查看',
                                'action-loc-key' => '',
                                'loc-key' => '',
                                'loc-args' => '',
                                'launch-image' => 'LaunchImage',
                            ),
                            // 'badge' => 1,
                            'sound' => 1,
                        ),
                        'url' => $remindInfo['url']
                    ),
                );
                $clients = $this->db->getRow("select client, client_type from r_client where cid ={$remindInfo['cid']} and isPushVaild=1 and isAcceptPush=1 and version>=2610");;
                if (!$clients) {
                    echo date('Y-m-d H:i:s').'ID为'.$remindInfo['id'].'的提醒项的cid 不符合'.PHP_EOL;
                    return $is_success;
                }
//            $clients = array('client_type'=>2,'cid'=>6918151,'client'=>'3d055b26c14486a2e5bfa8bf24949cf7a5252230');
                //开始更新
                switch ($clients['client_type']) {
                    case 1:
                        $postResult = $mipush->send(array($clients['client']), $androidData['payload']);
                        $is_success = $postResult['result'] == 'ok';
                        break;
                    case 2:
                        $postResult = $mipush->send(array($clients['client']), $iosData['payload'], 1);
                        $is_success = $postResult['result'] == 'ok';
                        break;
                    default :
                        echo date('Y-m-d H:i:s').'ID为'.$remindInfo['id'].'的提醒项的cid 不符合 cid:'.$remindInfo['cid'].' --client_type: '.$clients['client_type'].PHP_EOL;
                        break;
                }
            }
        return $is_success;

    }

    /**
     * cron 同步未开始闪购商品到提醒任务列表中,时间：未开始 前3分钟
     * 每分钟同步一次
     */
    public function pushFlashGoodsToRemindList () {
        exit;
        //所有未开始的商品
        $startCronTime = time();
        $time = bcadd(time() , 10*60);
        $sql = "select id from r_flash_sales where status = 0 and start_time >= $startCronTime and  start_time <=$time";
        $arrList =$this->db->getAll($sql);
        if (!$arrList) {
            echo date('Y-m-d H:i:s').' 10分钟内没有同步的闪购'.PHP_EOL;
            return false;
        }
        $arrId = [];
        foreach ($arrList as $key=>$val) {
            $arrId[]= $val['id'];
        }
        $result = [];
        //查询商品是否存在push列表中
        $sql = "select object_id from r_object_push where type = 1";
        $arrObject = $this->db->getAll($sql);
        $arrObjectId = [];
        if (!$arrObject) {
            echo date('Y-m-d H:i:s').' push存储列表为空'.PHP_EOL;
            $result = $arrId;
            echo date('Y-m-d H:i:s').'result'.json_encode($result,true).PHP_EOL;
        } else {
            echo date('Y-m-d H:i:s').' 循环push存储列表'.PHP_EOL;
            foreach ($arrObject as $key =>$val) {
                $arrObjectId[] = $val['object_id'];
            }
            $result = array_diff($arrId,(array)$arrObject);
            echo date('Y-m-d H:i:s').'result'.json_encode($result,true).PHP_EOL;
        }

        //push 到推送列表
        foreach ($result as $key=>$val) {
            $data = array(
                'object_id'=>$val,
                'type'=>1,
                'create_time'=>time(),
                'url'=>self::flashSchemeHead.$val
                );
            echo date('Y-m-d H:i:s').' push 到推送列表 start'.json_encode($data,true).PHP_EOL;
            $r =$this->db->insertRow('r_object_push',$data,0);
            echo date('Y-m-d H:i:s').' push 到推送列表 end'.var_export($r,true).PHP_EOL;
        }
    }
    /************************************************闪购提醒END**********************************************/

    public function setFeature($id,$is_featured){
        $is_featured = $is_featured ? 1 : 0;
        $update_time = time();
        $this->db->updateRowTable('r_flash_sales',compact('id','is_featured','update_time'));
    }
}